<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;



class HomeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    /**
    *	前台的登录页
    */
    public function HomeLogin()
    {
        return view('web/home/login/login');
    }

    /**
    *	前台的登录方法
    */
    public function HomeDoLogin(Request $request)
    {
        
    	$arr = $request -> all();

        if(empty($arr['username'])) {
            return back()->with('error','用户名不能为空，请输入用户名后登陆');
        }

        if(empty($arr['password'])) {
            return back()->with('error','密码不能为空，请输入正确的密码后登陆');
        }

    	$res = DB::table('user_create')->where('username',$arr['username'])->first();
    	// var_dump($res);die;
    	if(!$res) {
    		// 用户名不存在
    		return back()->with('error','用户名不存在，请确认后登陆');
    	}

    	if(Hash::check($arr['password'],$res['password'])){
           
            session(['uid'=>$res['id'],'username'=>$arr['username']]);
            // var_dump(session('username'));die;
    		return redirect('/');
    		// echo '登录主页';
    	} else {
    		// '密码匹配不正确';
    		return back()->with('error','密码不正确，请确认后登陆');
    	}
    }

    /**
    *	前台的注册页面
    */
    public function HomeRegist()
    {

    	return view('web/home/login/regist');
    }

    /**
    *	前台的注册处理方法
    */
    public function HomeDoRegist(Request $request)
    {
    	$data = $request->except('_token','vcode','repassword');

    	$this->validate($request,[
            'username'=>'required|unique:user_create|regex:/^\w{6,16}$/',
            'password'=>'required|regex:/^\S{6,18}$/|same:repassword',
            'repassword'=>'required',
            'email'=>'required|email',
            'phone'=>'required|regex:/^1[34578]\d{9}$/',
            ],[
            'username.required' =>'用户名不能为空',
            'username.unique' =>'用户名已存在',
            'username.regex' =>'用户名格式不正确',
            'password.required' =>'密码不能为空',
            'password.regex' =>'密码格式不正确',
            'password.same' =>'俩次密码不一致',
            'repassword.required' =>'确认密码不能为空',
            'email.required' =>'邮箱不能为空',
            'email.email' => '邮箱格式不正确',
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机号格式不正确',
            ]);

    	// 使用Hash加密  
    	$data['password'] = Hash::make($request->input('password'));

    	// 给默认状态值
    	$data["state"] = 1;
    	// 添加时间
    	$data['addtime'] = time();

    	// var_dump($data);
    	$res = DB::table('user_create')->insert($data);
    	if($res) {

    		return redirect('/login')->with('success','注册成功,请登录!');
    	} else {

    		// 注册失败
    		return back()->with('error','注册失败,请重新注册');
    	}

    }

    public function HomeLogout()
    {
        // unset(session());
        session(['uid'=>'','username'=>'']);
        return redirect('/');
    }

}
